package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.gypsumCompete;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.gypsumCompete.GypsumCompeteBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dto.CustomerBidDto;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.TGypsumCompete;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.AshGateExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CustomerBidExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ITGypsumCompeteService;
import com.xiaoxu.intranetweb.util.SzResult;
import io.swagger.models.auth.In;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/gypsumCompete")
public class GypsumCompeteController {
    @Autowired
    private GypsumCompeteBu gypsumCompeteBu;
    @Autowired
    private ITGypsumCompeteService gypsumCompeteService;

    //获取所有投标信息
    @GetMapping("/getAllGypsumCompetes")
    public SzResult getAllGypsumCompetes(
            @RequestParam(value = "page") Integer page,
            @RequestParam(value = "pageSize") Integer pageSize,
            @RequestParam(value = "title", required = false) String title,//标题
            @RequestParam(value = "startTime", required = false) String startTime,//开始时间
            @RequestParam(value = "endTime", required = false) String endTime,//结束时间
            @RequestParam(value = "bidType", required = false) Integer bidType,//竞标类型
            @RequestParam(value = "status", required = false) String status,//竞标状态
            HttpServletRequest request
    ) {
//        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return gypsumCompeteBu.getAllGypsumCompetes(page, pageSize, title, startTime, endTime, bidType, status, plantId);
    }

    //新增竞标addGypsumCompete
    @PostMapping("/addGypsumCompete")
    public SzResult addGypsumCompete(@RequestBody JSONObject jsonObject, HttpServletRequest request)  {
        String title = jsonObject.getString("title");
        String month = jsonObject.getString("month");
        String beginDate = jsonObject.getString("beginDate");
        String beginTDate = jsonObject.getString("beginTDate");
        Integer bidDays = jsonObject.getInteger("bidDays");
        Double minBid = jsonObject.getDouble("minBid");
        Integer maxDays = jsonObject.getInteger("maxDays");
//        Integer bidType = jsonObject.getInteger("bidType");
        Integer priceShow = jsonObject.getInteger("priceShow");
        String pdtId = jsonObject.getString("pdtId");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        try {
            return gypsumCompeteBu.addGypsumCompete(title, month,beginDate, beginTDate, bidDays, minBid, maxDays, priceShow, pdtId, token, plantId);
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }

    // 审批，就是将status变成10approveGypsumCompete
    @PostMapping("/approveGypsumCompete")
    public SzResult approveGypsumCompete(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String id = jsonObject.getString("id");
        Integer status = jsonObject.getInteger("status");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        try {
            return gypsumCompeteBu.approveGypsumCompete(id,status, token, plantId);
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }
    //    撤销标，在投标开始时间之前，等于删掉数据
//    public SzResult revokeGypsumCompete(
////            String id,
////            String token,
////            String plantId) throws Exception {
    @PostMapping("/revokeGypsumCompete")
    public SzResult revokeGypsumCompete(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String id = jsonObject.getString("id");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        try{
        return gypsumCompeteBu.revokeGypsumCompete(id, token, plantId);
    }catch (Exception e) {
        return SzResult.Error("服务出错，用户信息错误");
    }
    }

    //修改招标信息，在未到开始投标之前updateGypsumCompete
    @PostMapping("/updateGypsumCompete")
    public SzResult updateGypsumCompete(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String id = jsonObject.getString("id");
        String title = jsonObject.getString("title");
        String beginDate = jsonObject.getString("beginDate");
        String beginTDate = jsonObject.getString("beginTDate");
        Integer bidDays = jsonObject.getInteger("bidDays");
        String pdtId = jsonObject.getString("pdtId");
        String minBid = jsonObject.getString("minBid");
        Double minBidDouble = Double.parseDouble(minBid);
        Integer maxDays = jsonObject.getInteger("maxDays");
        Integer bidType = jsonObject.getInteger("bidType");
        Integer priceShow = jsonObject.getInteger("priceShow");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        try{
            return gypsumCompeteBu.updateGypsumCompete(id, title, beginDate, beginTDate,bidDays, pdtId, minBidDouble, maxDays, bidType, priceShow, token, plantId);
    }catch (Exception e) {
        return SzResult.Error("服务出错，用户信息错误");
    }
    }
////    归档
    @PostMapping("/archiveGypsumCompete")
    public SzResult archiveGypsumCompete(
            @RequestBody JSONObject jsonObject){

        String id = jsonObject.getString("id");
        Integer archived = jsonObject.getInteger("archived");
        return gypsumCompeteBu.archiveGypsumCompete(id,archived);
    }
    //    客户投标customerBid
    @PostMapping("/customerBid")
    public SzResult customerBid(@RequestBody JSONObject jsonObject, HttpServletRequest request)  {
//        String competeId = jsonObject.getString("competeId");
//        String pdtId = jsonObject.getString("pdtId");
//        BigDecimal price = jsonObject.getBigDecimal("price");
//        Integer day = jsonObject.getInteger("day");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        List<CustomerBidDto> customerBidDtos = JSONObject.parseArray(jsonObject.getString("customerBidDto"), CustomerBidDto.class);
        try {
            return gypsumCompeteBu.customerBid(customerBidDtos,token,plantId);
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }


    //    //    返回所有投标数据
    @GetMapping("/getAllCustomerBid")
    public SzResult getAllCustomerBid (
            @RequestParam(value = "page") Integer page,
            @RequestParam(value = "pageSize") Integer pageSize,
            @RequestParam(value = "pdtId", required = false) String pdtId,
            @RequestParam(value = "coId", required = false) String coId,
            @RequestParam(value = "competeId") String competeId,
            @RequestParam(value = "day", required = false) Integer day,
            HttpServletRequest request
    ){
        String plantId = request.getHeader("Plant-Id");
        try {
            return gypsumCompeteBu.getAllCustomerBid( page, pageSize, pdtId, coId, competeId, day, plantId);
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }
    //修改确认信息
    @PostMapping("/updateConfirmCustomerBid")
    public SzResult updateConfirmCustomerBid(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String id = jsonObject.getString("id");
        Integer winBid = jsonObject.getInteger("winBid");
        BigDecimal winBidPrice = jsonObject.getBigDecimal("winBidPrice");
//        Integer winBidDay = jsonObject.getInteger("winBidDay");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        try {
            return gypsumCompeteBu.updateConfirmCustomerBid(id, winBid, winBidPrice, token, plantId);
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }
//    查询石膏竞价vip客户
//     public SzResult getAllGypsumCompeteVipCustomer(Integer page,Integer pageSize,String pdtId,String coId,String plantId) throws Exception {
    @GetMapping("/getAllGypsumCompeteVipCustomer")
    public SzResult getAllGypsumCompeteVipCustomer(
            @RequestParam(value = "page") Integer page,
            @RequestParam(value = "pageSize") Integer pageSize,
            @RequestParam(value = "pdtId", required = false ) String pdtId,
            @RequestParam(value = "coId", required = false) String coId,
            @RequestParam(value = "month", required = false) Integer month,
            HttpServletRequest request
    ) {
        String plantId = request.getHeader("Plant-Id");
        try {
        return gypsumCompeteBu.getAllGypsumCompeteVipCustomer(page, pageSize, pdtId, coId,month, plantId);
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
}
//新增石膏竞价vip客户

    @PostMapping("/addGypsumCompeteVipCustomer")
    public   SzResult addGypsumCompeteVipCustomer(
            @RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String coId = jsonObject.getString("coId");
        String pdtId = jsonObject.getString("pdtId");
        BigDecimal price = jsonObject.getBigDecimal("price");
        Integer days = jsonObject.getInteger("days");
        String months = jsonObject.getString("months");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
            return gypsumCompeteBu.addGypsumCompeteVipCustomer( coId, pdtId, price, days, months, token, plantId);

    }

//    下载投标数据的excel
    @PostMapping("/exportCustomerBidExcel")
    public SzResult exportCustomerBidExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response) throws Exception {
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
//     String startTime, String endTime, String coSupply, String co, List<String> product, String truckNo, String iccardno, Integer isEmpty,String cpyClass,String pdtClass
        String competeId = "";
        List<String> product = new ArrayList<>();
        Integer isEmpty = null, pdtClassId = null;
        if (form != null) {
            if (form.get("competeId") != null) {
                competeId = form.get("competeId").toString();
            }
        }
        QueryWrapper<TGypsumCompete> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", competeId);
        TGypsumCompete gypsumCompete1 = gypsumCompeteService.getOne(queryWrapper1);
        if (gypsumCompete1.getIfConfirm() ==0){
            return SzResult.Error("导出失败，该标还未最终确认");
        }
        Future<List<CustomerBidExcelEn>> listFuture = gypsumCompeteBu.exportCustomerBidExcel(competeId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<CustomerBidExcelEn> customerBidExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("石膏竞价结果", "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CustomerBidExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("石膏竞价结果")
                .doWrite(customerBidExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
        return SzResult.Success();
    }

//    手动执行
    //    public SzResult executeGypsumCompeteVipCustomer(
    //            String id,
    //            String token,
    //            String plantId) throws Exception {
    @PostMapping("/executeGypsumCompeteVipCustomer")
    public SzResult executeGypsumCompeteVipCustomer(
            @RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return gypsumCompeteBu.executeGypsumCompeteVipCustomer(id, token, plantId);
    }
//    删除数据
//      @Transactional(rollbackFor = Exception.class)
//    public SzResult deleteGypsumCompeteVipCustomer(
//            String id) throws Exception {
    @PostMapping("/deleteGypsumCompeteVipCustomer")
    public SzResult deleteGypsumCompeteVipCustomer(
            @RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return gypsumCompeteBu.deleteGypsumCompeteVipCustomer(id, token, plantId);
    }
}
